import { createRequest as request } from '../utils/request'
import CacheStore from '../utils/cacheStore'
import Tools from '../utils/tools'

const login2 = (query) => {
    return new Promise(((resolve, reject) => {
        request('POST', '/sys/login', query, {}, {
            crypt: ''
        }).then(res => {
            let data = res.body
            CacheStore.setCookie("access_token", 'Bearer ' + data.access_token, data.expires_in * 1000)
            CacheStore.setCookie("refresh_token", data.refresh_token, 2592000 * 1000)
            let date = new Date()
            date.setTime(date.getTime() + data.expires_in * 1000)
            // 将access_token的过期时间也存入cookie
            CacheStore.setCookieWithExpires('token_expires', date.toGMTString(), date.toGMTString())
            resolve()
        }).catch(res => {
            reject(res)
        })
    }))
}

const refresh = () => {
    return new Promise(((resolve, reject) => {
        request('POST', '/sys/refresh', {}, {}, {
            crypto: ''
        }).then(res => {
            let data = res.body
            CacheStore.setCookie("access_token", data.token_type + ' ' + data.access_token, data.expires_in * 1000)
            resolve()
        }).catch(res => {
            reject(res)
        })
    }))
}

const current = () => {
    return new Promise(((resolve, reject) => {
        request('GET', '/user/current', {}, {}, {
            crypt: ''
        }).then(res => {
            let data = res.body
            let userInfo = {userid: data.userid, account: data.account, username: data.username}
            // userInfo暂时不设过期时间了，只要token过期了，访问时就同时清除userInfo
            // 后续考虑，添加一个token过期时间记录cookie，将userInfo的过期时间设置为跟token同步
            CacheStore.setCookieWithExpires("userInfo", Tools.stringIfy(userInfo), CacheStore.getCookie('token_expires'))
            resolve(userInfo)
        }).catch(res => {
            reject(res)
        })
    }))
}

const register = (query) => {
    return request('POST', 'user/register', {}, query, {
        crypto: ''
    })
}

export default {
    login2,
    current,
    register
}
